package com.ruoyi.activiti.bpmnparse.x6translator;

import com.alibaba.fastjson.JSON;
import com.ruoyi.activiti.bpmnparse.BpmnHelper;
import com.ruoyi.activiti.bpmnparse.Translator;
import com.ruoyi.activiti.domain.CustomProcess;
import com.ruoyi.activiti.mapper.CustomProcessMapperHis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class X6Helper implements BpmnHelper {
    @Autowired
    private CustomProcessMapperHis customProcessMapperHis;
    @Override
    public String getBpmnType(Map<String,Object> sourceMap) {
        Map<String,Object> data = (Map<String, Object>) sourceMap.get("data");
        if(data != null) {
            return (String) data.get(Translator.BPMN_TYPE);
        } else {
            return null;
        }
    }

    @Override
    public String getBpmnKey(List<Map<String, Object>> sourceListMap, String id) {
        for (Map<String, Object> map : sourceListMap) {
            String mapId = (String) map.get("id");
            if(id.equals(mapId)) {
                Map<String,Object> dataMap = (Map<String, Object>) map.get("data");
                return (String) dataMap.get("id");
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> getBpmnDataById(List<Map<String, Object>> listMap, String id) {
        for (Map<String, Object> map : listMap) {
            String nodeId = (String) map.get("id");
            if(id.equals(nodeId)) {
                return (Map<String, Object>) map.get("data");
            }
        }
        return null;
    }
    public Map<String,Object> getBpmnData(String procDefId,String taskDefKey){
        CustomProcess customProcess = customProcessMapperHis.selectByProcDefId(procDefId);
        String x6GraphData = customProcess.getGraphData();
        Map<String,Object> x6Map = JSON.parseObject(x6GraphData);
        List<Map<String,Object>> listMap = (List<Map<String, Object>>) x6Map.get("cells");
        return getBpmnDataById(listMap,taskDefKey);
    }
    public Object getValueByDataKey(String procDefId,String taskDefKey,String key){
        CustomProcess customProcess = customProcessMapperHis.selectByProcDefId(procDefId);
        String x6GraphData = customProcess.getGraphData();
        Map<String,Object> x6Map = JSON.parseObject(x6GraphData);
        List<Map<String,Object>> listMap = (List<Map<String, Object>>) x6Map.get("cells");
        Map<String,Object> data =  getBpmnDataById(listMap,taskDefKey);
        return data.get(key);
    }
}
